package com.amorcloud.pig.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;

import com.amorcloud.pig.R;
import com.amorcloud.pig.bean.UserInfoBean;
import com.amorcloud.pig.utils.UserDaoUtils;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class SplashActivity extends BaseActivity {

    private Button btn_skip;
    private Timer timer;

    @Override
    protected void init() {
        setContentView(R.layout.activity_splash);
        initAdmin();
        btn_skip = (Button) findViewById(R.id.btn_skip);
    }

    //设定倒计时时长 n 单位 s
    private int time = 5;
    //初始化 Handler
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    btn_skip.setText("跳过(" + time + ")");
                    break;
                case 1:
                    startActivity(new Intent(SplashActivity.this, SigninActivity.class));
                    finish();
            }
            super.handleMessage(msg);
        }
    };

    /** skip Button 点击事件 */
    public void onclick(View view) {
        handler.sendEmptyMessage(1);
    }

    @Override
    protected void onResume() {
        timer = new Timer(true);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                time--;
                handler.sendEmptyMessage((time == 0 ? 1 : 0));
            }
        }, 1000, 1000);
        super.onResume();
    }

    @Override
    protected void onPause() {
        timer.cancel();
        timer = null;
        super.onPause();
    }

    private void initAdmin() {
        List<UserInfoBean> list = UserDaoUtils.queryWhere("where IS_ADMIN=?", "1");
        if(list == null || list.size() < 1) {
            UserInfoBean user = new UserInfoBean();
            user.setIsAdmin("1");
            user.setUserName("admin");
            user.setPasswrod("admin");
            UserDaoUtils.insertUser(user);
        }
    }
}
